package com.ubhave.powertrackernof1;

import java.util.Date;

import com.ubhave.powertrackernof1.R;

//import android.app.Activity;
import android.support.v4.app.FragmentActivity;
//import android.app.DialogFragment;
import android.support.v4.app.DialogFragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class PowerTrackerActivity extends FragmentActivity implements LoginDialogListener{
    
	int day;
	int qday;
	int week;
	Date currentDate;
	String[] inhibitedWeeks;
	boolean inhibited;
		
	SharedPreferences settings;
	LifeGuideConnector lgc;
	SharedPreferences.Editor editor;
	
	String usr;
	String intervention;
	
	String threadTest;
	PageSensorLogger psl;
	PageLogger pl;
	
	boolean showDialog;
	
	PowerTrackerSharedPreferenceChangeListener prefChangeListener;
	
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        //StrictMode.setThreadPolicy(policy);
        
        settings=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        editor = settings.edit();
        lgc=new LifeGuideConnector(settings,this);
           
        //this makes sure the preference defaults are loaded the first time the app is run by assuming an empty authkey means it hasn't been run before. This is ugly - do this a better way.
        if(settings.getString("authkey", "").equals("")){
        	PreferenceManager.setDefaultValues(PowerTrackerApplication.getContext(), R.xml.preferences, false);
        }
    	
        usr = settings.getString("LifeGuideUser", "");
		intervention = settings.getString("LifeGuideInterventionId", "");
		
		TextView welcomeText = (TextView)findViewById(R.id.WelcomeText);
		welcomeText.setText("Welcome "+usr);
		
		TextView versionText = (TextView)findViewById(R.id.VersionText);
		try {
			versionText.setText("version: "+getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		showDialog=false;
        
			
		//Handle Async Logging using internal async class	
		if(settings.getBoolean("SensorsOn", false))
			psl = new PageSensorLogger(this);
		pl = new PageLogger(this);

		class AsyncLog extends AsyncTask{

			@Override
			protected Object doInBackground(Object... params) {
								
				if(settings.getString("authkey", "").equals("")){
					
					DialogFragment dialog = new LoginDialog();
					dialog.show(getSupportFragmentManager(), "LoginDialog");
					//dialog.show(getFragmentManager(), "LoginDialog");
				}
		        		        				
				try {
		        	//Log.i("POWeR Tracker Special: ","AuthKey Check");
					pl.makeLog();
						        
					//Basic Sensors
					Log.i("POWeR Tracker: ", "Sensor on?: "+settings.getBoolean("SensorsOn", false));
				
					if(settings.getBoolean("SensorsOn", false)){
						psl.makeLog();
					}
		        	
					//check and store current app version
					if(!settings.getString("currentAppVersion", "").equals(getPackageManager().getPackageInfo(getPackageName(), 0).versionName)){
						if(!usr.equals("")&&!intervention.equals("")){
							editor.putString("currentAppVersion", getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
							editor.putString("sensorLog", settings.getString("sensorLog", "")+"Push Sensor: ChangeAppVersion("+getPackageManager().getPackageInfo(getPackageName(), 0).versionName+") "+"TimeStamp("+new Date()+"), ");
							editor.commit();
							lgc.postVar(intervention, usr, "user", "currentAppVersion", settings.getString("currentAppVersion", ""),settings.getString("authkey",""));
						}
					}
					
					//check and store current android version
					if(!settings.getString("currentAndroidVersion", "").equals(Build.VERSION.RELEASE)){
						if(!usr.equals("")&&!intervention.equals("")){
							editor.putString("currentAndroidVersion", Build.VERSION.RELEASE);
							editor.putString("sensorLog", settings.getString("sensorLog", "")+"Push Sensor: ChangeAndroidVersion("+Build.VERSION.RELEASE+") "+"TimeStamp("+new Date()+"), ");
							editor.commit();
							lgc.postVar(intervention, usr, "user", "currentAndroidVersion", settings.getString("currentAndroidVersion", ""),settings.getString("authkey",""));
						}
					}
					
					//check and store current phone
					if(!settings.getString("currentPhone", "").equals(Build.MANUFACTURER+"-"+Build.MODEL)){
						if(!usr.equals("")&&!intervention.equals("")){
							editor.putString("currentPhone", Build.MANUFACTURER+"-"+Build.MODEL);
							editor.putString("sensorLog", settings.getString("sensorLog", "")+"Push Sensor: ChangePhone("+Build.MANUFACTURER+"-"+Build.MODEL+") "+"TimeStamp("+new Date()+"), ");
							editor.commit();
							lgc.postVar(intervention, usr, "user", "currentPhone", settings.getString("currentPhone", ""),settings.getString("authkey",""));
						}
					}
					
		        } catch (PowerTrackerInvalidAuthKeyException e) {
		        	//Log.i("POWeR Tracker Special: ","InvalidAuthKey Logging");
		        	invalidKey();		        	
		        } catch (NameNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
		        
				return null;
			}
			
			
		}
		
		//execute the async log
		new AsyncLog().execute(this);
		

		
		//Set the app start date
		currentDate = new Date();
    	
    	if(settings.getString("appStart", "").equals("")){
    		editor.putString("appStart", currentDate.getDate()+"-"+currentDate.getMonth()+"-"+currentDate.getYear());
            editor.commit();
            Log.i("POWeR Tracker: ","set appStart "+currentDate.getDate()+"-"+currentDate.getMonth()+"-"+currentDate.getYear());
    	}
		
		    	
    	//Handle validating questionnaire button and current day and week
    	setDay();
		
		
		int weekStars=new Integer(settings.getString("week"+week+"stars", "0"));
		
		if(weekStars>7)
			weekStars=7;
				
		ImageView starsView = (ImageView)findViewById(R.id.MenuStars);
		starsView.setImageDrawable(getResources().getDrawable(getResources().getIdentifier("stars"+weekStars,"drawable",getPackageName())));
		
		if(settings.getString("interventionMode", "").equals("2")){
			View qButton = findViewById(R.id.QuestionnaireButton);
			qButton.setVisibility(View.GONE);
			View qLabel = findViewById(R.id.QuestionnaireButtonLabel);
			qLabel.setVisibility(View.GONE);
		}
	}
    
    
    @Override
    public void onStart() {
    	super.onStart();
    	//Check if inhibitor values are loaded and try to get them if not.
    	inhibitGet();
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        //settings.unregisterOnSharedPreferenceChangeListener(prefChangeListener);
        if(psl!=null)
        	psl.stopLocationSensing();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if(psl!=null)
        	psl.resumeLocationSensing();
        
       setDay(); 
        
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        	
    	switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; go home
                goHome();
                return true;
            case R.id.home:
                // app icon in options clicked; go home
            	goHome();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.o_menu, menu);
        return true;
    }
    
    public void goHome(){
    	Intent intent = new Intent(this, PowerTrackerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    public void goViewGoals(View v){
    	inhibitCheck();
    	//Log.i("POWeR Tracker Special: ","Inhibit "+inhibited+" - "+settings.getString("usageInhibitorWeeks", "")+" - "+week);
    	if((!inhibited||!settings.getBoolean("UsageInhibitorOn", true)||settings.getString("interventionMode", "").equals("2"))&&!usr.equals("")&&!intervention.equals("")){
    		Intent myIntent = new Intent().setClass(this, ViewGoalsActivity.class);
        	startActivityForResult(myIntent, 0);
    	}
    	else if(inhibited)
    		Toast.makeText(this, getResources().getString(R.string.usageInhibitorError), Toast.LENGTH_SHORT).show();
    	else if(usr.equals(""))
    		Toast.makeText(this, "Please set username in settings before using POWeR Tracker", Toast.LENGTH_SHORT).show();
    	else if(intervention.equals(""))
    		Toast.makeText(this, "Intervention Id is not correctly set, please contact a study organiser", Toast.LENGTH_SHORT).show();
    }
    
    public void goInfo(View v){
    	inhibitCheck();
    	if((!inhibited||!settings.getBoolean("UsageInhibitorOn", true)||settings.getString("interventionMode", "").equals("2"))&&!usr.equals("")&&!intervention.equals("")){
    		Intent myIntent = new Intent().setClass(this, InfoMenuActivity.class);
    		startActivityForResult(myIntent, 0);
    	}
    	else if(inhibited)
    		Toast.makeText(this, getResources().getString(R.string.usageInhibitorError), Toast.LENGTH_SHORT).show();
    	else if(usr.equals(""))
    		Toast.makeText(this, "Please set username in settings before using POWeR Tracker", Toast.LENGTH_SHORT).show();
    	else if(intervention.equals(""))
    		Toast.makeText(this, "Intervention Id is not correctly set, please contact a study organiser", Toast.LENGTH_SHORT).show();
    	
    }
    
    public void goSettings(View v){
    	Intent settingsActivity = new Intent(getBaseContext(), PowerTrackerPreferences.class);
    	//startActivity(settingsActivity);
    	startActivityForResult(settingsActivity,0);
    }
    
    public void goDiaries(View v){
    	inhibitCheck();
    	if((!inhibited||!settings.getBoolean("UsageInhibitorOn", true)||settings.getString("interventionMode", "").equals("2"))&&!usr.equals("")&&!intervention.equals("")){
    		Intent myIntent = new Intent(getBaseContext(), DiariesMenuActivity.class);
    		startActivity(myIntent);
    	}
    	else if(inhibited)
    		Toast.makeText(this, getResources().getString(R.string.usageInhibitorError), Toast.LENGTH_SHORT).show();
    	else if(usr.equals(""))
    		Toast.makeText(this, "Please set username in settings before using POWeR Tracker", Toast.LENGTH_SHORT).show();
    	else if(intervention.equals(""))
    		Toast.makeText(this, "Intervention Id is not correctly set, please contact a study organiser", Toast.LENGTH_SHORT).show();
    	
    }
    
    public void goQuestionnaire(View v){
    	    	    	
    	if((!settings.getBoolean("QDone-Daily-"+qday, false)||!settings.getBoolean("QuestionnaireInhibitorOn", true))&&!usr.equals("")&&!intervention.equals("")&&(currentDate.getHours()>16||currentDate.getHours()<11)||!settings.getBoolean("QuestionnaireInhibitorOn", true)){
    		Intent myIntent = new Intent(getBaseContext(), QuestionnaireActivity.class);
			myIntent.putExtra("page", "1");
			myIntent.putExtra("name", "GoalEffort");
			myIntent.putExtra("orientation", "H");
			myIntent.putExtra("questionsPerPage", "3");
			myIntent.putExtra("type", "Likert");
			myIntent.putExtra("scale", "7");
			myIntent.putExtra("labelMode", "0");
			myIntent.putExtra("title", " ");
			myIntent.putExtra("multipart", "0");
			myIntent.putExtra("forGoal", "1");
			startActivity(myIntent);
    	}
    	else if(settings.getBoolean("QDone-Daily-"+qday, false)){
    		Toast.makeText(this, "You have done your Daily Questionnaires for the Day. Please return to do them tomorrow.", Toast.LENGTH_SHORT).show();
    	}
    	else if(usr.equals(""))
    		Toast.makeText(this, "Please set username in settings before using POWeR Tracker", Toast.LENGTH_SHORT).show();
    	else if(intervention.equals(""))
    		Toast.makeText(this, "Intervention Id is not correctly set, please contact a study organiser", Toast.LENGTH_SHORT).show();
    	else if(currentDate.getHours()<17&&currentDate.getHours()>10){
    		Toast.makeText(this, "Daily Questionnaires can only be completed between the hours of 5pm and 11am. Please wait till this period to enter a questionnaire.", Toast.LENGTH_LONG).show();
    	}
    	
    }
    
    public void inhibitGet(){
    	
    	lgc=new LifeGuideConnector(settings);
    	usr = settings.getString("LifeGuideUser", "");
		intervention = settings.getString("LifeGuideInterventionId", "");
    	
    	class AsyncInhibitorGet extends AsyncTask{
    		
    		boolean initialVarsFail = false;

			@Override
			protected Object doInBackground(Object... params) {
				//Get Inhibited weeks if not set and not IM2
				if(!settings.getString("interventionMode", "").equals("2")&&settings.getString("usageInhibitorWeeks", "").equals("")&&!usr.equals("")&&!intervention.equals("")){
					try{
						String weeks = lgc.getVar(intervention, usr, "user", "usageInhibitorWeeks",settings.getString("authkey",""));
						if(weeks!=null){
							editor.putString("usageInhibitorWeeks", weeks);
							editor.commit();
							Log.i("POWeR Tracker: ","set usageInhibitorWeeks "+weeks);
						}
						else{
							//Toast.makeText(PowerTrackerApplication.getContext(), "Failed to load Initial Variables from server - please insure you have a working net connection", Toast.LENGTH_SHORT).show();
							initialVarsFail=true;
						}
					} catch (PowerTrackerInvalidAuthKeyException e) {
						Log.i("POWeR Tracker Special: ","InvalidAuthKey Inhib");
						invalidKey();
					}
				}
				return null;
			}
			
			protected void onPostExecute(Object result) {
				if(initialVarsFail&&settings.getString("interventionMode", "").equals("1"))
					Toast.makeText(PowerTrackerApplication.getContext(), "Failed to load Initial Variables from server - please insure you have a working net connection", Toast.LENGTH_LONG).show();
		    }
		};
		
		//execute the async log
		new AsyncInhibitorGet().execute(this);
    }
    
    
    public void inhibitCheck(){
    	    	
		inhibitGet();	
    	
    	//Detect if on inhibited week
    	inhibited=false;
    	
    	if(!settings.getString("usageInhibitorWeeks", "").equals("")){
    		   		
    		String weeks=settings.getString("usageInhibitorWeeks", "");
    		inhibitedWeeks=weeks.split(",");
    		for(String w:inhibitedWeeks){
    			if(new Integer(w).intValue()==week)
    				inhibited=true;
    			
    		}
    	}
    	else
    		inhibited=true;
    	
        	
    }
    
    public void invalidKey(){
		DialogFragment dialog = new LoginDialog();
		Bundle errorBundle = new Bundle();
	    errorBundle.putString("error", "Your Authentication Key is invalid, expired, or is missing. Please Log In.");
	    dialog.setArguments(errorBundle);
	    //dialog.show(this.getFragmentManager(), "LoginDialog");
	    if(!showDialog){
	    	showDialog=true;
	    	dialog.show(this.getSupportFragmentManager(), "LoginDialog");
    	}
	    
	}
    
  	@Override
	public void onLoginDialogPositiveClick() {
		// TODO Auto-generated method stub
  		//Log.i("POWeR Tracker Special: ","Clicked OK");
  		showDialog=false;
  		finish();
  		startActivityForResult(getIntent(),0);
	}


	@Override
	public void onLoginDialogNegativeClick() {
		// TODO Auto-generated method stub
		//Log.i("POWeR Tracker Special: ","Clicked Cancel");
		//goHome();
		showDialog=false;
	}
	
	
	//Handle validating questionnaire button and current day and week
	public void setDay(){
		String[] startDateString = settings.getString("appStart", "").split("-");
		Date startDate = new Date(new Integer(startDateString[2]),new Integer(startDateString[1]),new Integer(startDateString[0]));
		currentDate = new Date();
		long diff = currentDate.getTime()-startDate.getTime();
		double daysDiff = diff/(1000*60*60*24);
		day = new Integer(new Double(daysDiff).intValue()+1);
		
		if(currentDate.getHours()<11)
			qday=day-1;
		else
			qday=day;
		
		week=new Double(Math.ceil(new Double(day/7.0))).intValue();
		
		setQButton();
	}
	
	public void setQButton(){
		if(settings.getBoolean("QDone-Daily-"+qday, false))
			findViewById(R.id.QuestionnaireButton).setBackgroundDrawable(getResources().getDrawable(R.drawable.btntick));
		
	}
 }